package com.example.myapplication.function.musicmode

import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Log

/**
 * 2. 增强的音频录制类（集成降噪）
 */

class EnhancedAudioRecorder(
    private val onAudioData: (FloatArray) -> Unit,
    private val enableNoiseFilter: Boolean = true
) {
    private var recorder: AudioRecord? = null
    private var isRecording = false
    private var recordingThread: Thread? = null
    private val noiseFilter = AudioNoiseFilter()
    
    // 音频统计
    private var silenceCounter = 0
    private val energyHistory = FloatArray(10) { 0f }
    private var historyIndex = 0

    companion object {
        private const val SAMPLE_RATE = 44100
        private const val CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO
        private const val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT
        private const val BUFFER_SIZE = 1024
        
        // 降噪参数
        private const val SILENCE_DURATION_THRESHOLD = 20 // 连续静音帧数阈值
        private const val ENERGY_HISTORY_SIZE = 10
    }

    fun startRecording() {
        if (isRecording) {
            Log.w("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Already recording")
            return
        }

        try {
            val minBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT)
            if (minBufferSize == AudioRecord.ERROR_BAD_VALUE) {
                Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Invalid buffer size")
                return
            }

            recorder = AudioRecord(
                MediaRecorder.AudioSource.VOICE_RECOGNITION, // 使用语音识别音源，自带一些降噪
                SAMPLE_RATE,
                CHANNEL_CONFIG,
                AUDIO_FORMAT,
                minBufferSize * 2
            )

            when (recorder?.state) {
                AudioRecord.STATE_UNINITIALIZED -> {
                    Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "AudioRecord not initialized")
                    return
                }
                AudioRecord.STATE_INITIALIZED -> {
                    Log.d("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "AudioRecord initialized successfully")
                }
            }

            recorder?.startRecording()
            isRecording = true
            resetStatistics()

            recordingThread = Thread(EnhancedRecordingRunnable())
            recordingThread?.start()
            
            Log.d("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Recording started with noise filter: $enableNoiseFilter")

        } catch (e: SecurityException) {
            Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Audio record permission denied", e)
        } catch (e: Exception) {
            Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Error starting recording", e)
        }
    }

    fun stopRecording() {
        if (!isRecording) return

        isRecording = false
        
        try {
            recorder?.let { audioRecord ->
                if (audioRecord.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
                    audioRecord.stop()
                }
                audioRecord.release()
            }
            recorder = null
            
            recordingThread?.join(1000)
            recordingThread = null
            
            Log.d("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Recording stopped")
        } catch (e: Exception) {
            Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Error stopping recording", e)
        }
    }

    private fun resetStatistics() {
        silenceCounter = 0
        energyHistory.fill(0f)
        historyIndex = 0
    }

    private inner class EnhancedRecordingRunnable : Runnable {
        override fun run() {
            val buffer = ShortArray(BUFFER_SIZE)
            val floatBuffer = FloatArray(BUFFER_SIZE)
            
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)

            while (isRecording) {
                try {
                    val readResult = recorder?.read(buffer, 0, BUFFER_SIZE) ?: 0
                    
                    when {
                        readResult == AudioRecord.ERROR_INVALID_OPERATION -> {
                            Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "ERROR_INVALID_OPERATION")
                            break
                        }
                        readResult == AudioRecord.ERROR_BAD_VALUE -> {
                            Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "ERROR_BAD_VALUE")
                            break
                        }
                        readResult > 0 -> {
                            // 转换为float数组
                            for (i in 0 until readResult) {
                                floatBuffer[i] = buffer[i] / 32768.0f
                                // 限制在-1.0到1.0之间
                                if (floatBuffer[i] > 1.0f) floatBuffer[i] = 1.0f
                                if (floatBuffer[i] < -1.0f) floatBuffer[i] = -1.0f
                            }
                            
                            // 应用降噪处理
                            val processedData = if (enableNoiseFilter) {
                                applyAdvancedNoiseReduction(floatBuffer.copyOf(readResult))
                            } else {
                                floatBuffer.copyOf(readResult)
                            }
                            
                            // 回调处理后的音频数据
                            onAudioData(processedData)
                        }
                        readResult == 0 -> {
                            Thread.sleep(10)
                        }
                    }
                } catch (e: Exception) {
                    Log.e("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Error in recording thread", e)
                    break
                }
            }
            
            Log.d("com.example.myapplication.function.musicmode.EnhancedAudioRecorder", "Enhanced recording thread finished")
        }
        
        /**
         * 应用高级降噪处理
         */
        private fun applyAdvancedNoiseReduction(audioData: FloatArray): FloatArray {
            // 1. 计算当前帧能量
            val currentEnergy = calculateFrameEnergy(audioData)
            
            // 2. 更新能量历史
            updateEnergyHistory(currentEnergy)
            
            // 3. 计算动态阈值
            val dynamicThreshold = calculateDynamicThreshold()
            
            // 4. 检测静音
            if (currentEnergy < dynamicThreshold) {
                silenceCounter++
                // 如果连续静音时间过长，返回空数据
                if (silenceCounter > SILENCE_DURATION_THRESHOLD) {
                    return FloatArray(audioData.size) { 0f }
                }
            } else {
                silenceCounter = 0
            }
            
            // 5. 应用实时噪音过滤
            var filteredData = noiseFilter.filterNoiseRealTime(audioData)
            
            // 6. 如果能量仍然很低，进一步衰减
            val filteredEnergy = calculateFrameEnergy(filteredData)
            if (filteredEnergy < dynamicThreshold * 1.5f) {
                val attenuation = filteredEnergy / (dynamicThreshold * 1.5f)
                for (i in filteredData.indices) {
                    filteredData[i] *= attenuation
                }
            }
            
            return filteredData
        }
        
        private fun calculateFrameEnergy(audioData: FloatArray): Float {
            var sum = 0f
            for (sample in audioData) {
                sum += sample * sample
            }
            return sum / audioData.size
        }
        
        private fun updateEnergyHistory(currentEnergy: Float) {
            energyHistory[historyIndex] = currentEnergy
            historyIndex = (historyIndex + 1) % ENERGY_HISTORY_SIZE
        }
        
        private fun calculateDynamicThreshold(): Float {
            // 计算能量历史的平均值作为动态阈值
            var sum = 0f
            var count = 0
            for (energy in energyHistory) {
                if (energy > 0f) {
                    sum += energy
                    count++
                }
            }
            
            val average = if (count > 0) sum / count else 0.001f
            return average * 0.5f // 使用平均值的50%作为阈值
        }
    }
    
    fun isRecording(): Boolean = isRecording
    
    fun getSampleRate(): Int = SAMPLE_RATE
    
    fun enableNoiseFilter(enable: Boolean) {
        // 可以在运行时切换降噪开关
        // 注意：需要在非录音状态下调用
    }
}